
    /**  
    * @Title: TypeToType.java
    * @Package com.utils.typetotype
    * @Description: 
    * @author likai
    * @date 2016年8月31日
    * @version V1.0  
    */
    
package com.utils.transtype;


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.supers.exception.ExceptionUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



/**
    * @ClassName: TypeToType
    * @Description: 类型转换工具类
    * @author likai
    * @date 2016年8月31日
    *
    */

public class TransType{
	public static Logger log = LoggerFactory.getLogger(TransType.class);

	/**
	 * Map<String, String>转成xml
	 * @param arr
	 * @return
	 */
	public static String mapToXml(HashMap<String, String> arr) {
		String xml = "<xml>";		
		Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			String key = entry.getKey();
			String val = entry.getValue();
			xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
		}

		xml += "</xml>";
		return xml;
	}

	 /**
     * @description 将xml字符串转换成Map<String, String>
     * @param xml
     * @return Map
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map xmlToMap(String xml) {
        Map<String, String> map = new HashMap();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator iter = rootElt.elementIterator(); 
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                String title = recordEle.getName();
                String value=recordEle.getText();
                map.put(title, value);
             
            } 
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
	
    
   
	
	/**
     * @description 将对象转换为json字符串
     * @param Object
     * @return json
     */
	public static String objectToJson(Object object) {
    	JSONObject jsonObject = JSONObject.fromObject(object);
    	String json=jsonObject.toString();
        return json;
    }
	
	/**
     * @description 将对象转换为json字符串
     *
     * @param Object
     * @return json
     */
	public static String toJson(Object obj) {	
		Gson gson = new Gson();
		return gson.toJson(obj);		
	}		
	
	 /**
     * @description 将json字符串转换为指定类型的对象
     *  只能转换json字符串，json数组字符串不行
     * @param json
     * @return Object
     */
	@SuppressWarnings({ "static-access", "unchecked" })
	public static <T> T jsonToObject(String json,Class<T> classType) {
    	JSONObject jsonObject = JSONObject.fromObject(json);
    	 T object=(T)jsonObject.toBean(jsonObject, classType);
        return object;
    }
	
	 /**
     * @param <T>
	 * @description 将json字符串转换为指定类型的对象集合
	 * 
     *  只能转换json字符串，json数组字符串不行
     * @param json
     * @return Object
     */
	@SuppressWarnings({  "unchecked", "deprecation" })
	public static <T> List<T>  jsonToObjectList(String json,Class<T> classType) {
		JSONArray jsonObject =JSONArray.fromObject(json);
		List<T> list=JSONArray.toList(jsonObject, classType);
        return list;
    }

	/**
     * @description 将json字符串转换为指定类型的对象
     * 可将json数组字符串转为list
     * 
     * @param json，Type为class
     * @return Object
     */
	public static Object fromJson(String str,Type type){
		Gson gson = new Gson();
		return gson.fromJson(str, type);
	}

	
	/**
     * @description 将对象转为map
     * @param Object
     * @return map
     */
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> beanToMap(Object obj) {  
        if(obj == null){  
            return null;  
        }        
        if(obj instanceof Map){  
            return (Map<String, Object>) obj;  
        }       
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
  
                // 过滤class属性  
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
  
                    map.put(key, value);  
                }  
  
            }  
  		  System.out.println(map.toString());

        } catch (Exception e) {  
        	log.error("beanToMap Error:"+ExceptionUtils.getExceptionMessage(e));
            throw new RuntimeException();
        }  
  
        return map;  
  
    }  
	
	
	
	/**
     * @description 将map转换为bean
     * @param 
     * @return 
     */
	@SuppressWarnings("rawtypes")
	public static <T> T mapToBean(Class<T> clazz, Map<String, Object> map) {
		if (map == null) {
			return null;
		}
		// 创建对象
		T instance = null;
		try {
			instance = clazz.newInstance();
			if (instance == null) {
				throw new Exception();
			}
		}
		catch (Exception e) {
			return null;
		}
		Map<String, Object> newMap = new HashMap<String, Object>();
		for (Map.Entry<String, Object> en : map.entrySet()) {
			newMap.put(columnSetMethod(en.getKey()), en.getValue());
		}
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			String mname = method.getName();
			if (mname.startsWith("set")) {
				Class[] ptypes = method.getParameterTypes();
				Object v = newMap.get(mname);
				if (v != null && ptypes.length == 1) {
					try {
						method.invoke(instance, v);
					}
					catch (Exception e) {
						e.getStackTrace();
					}
				}
			}
		}
		return instance;
	}		
	
	
	
	
	
	/**
     * @description 将maplist转换为beanlist
     * @param Object
     * @return map
     */
	public static <T> List<T> mapListToBeanList(Class<T> clazz, List<Map<String, Object>> mapList) {
		List<T> rstList = new ArrayList<T>();
		for (Map<String, Object> map : mapList) {
			rstList.add(mapToBean(clazz, map));
		}
		return rstList;
	}
	
	
	
	
	

	/**
	 * 数据库字段转换为set方法
	 * 
	 * @param column
	 * @return
	 */
	public static String columnSetMethod(String column) {
		return "set" + columnToField2(column);
	}
	
	
	/**
	 * 转换有下划线的String，第一个字母大写，下划线的后一个字母大写
	 * 
	 * @param str
	 * @return
	 */
	public static String columnToField2(String str) {
		String[] arr = str.split("_");
		if (arr != null && arr.length > 1) {
			String rstStr = arr[0].substring(0, 1).toUpperCase() + arr[0].substring(1);
			for (int i = 1; i < arr.length; i++) {
				rstStr += arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1);
			}
			return rstStr;
		}
		else {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
	}
	

	/**
	 * 转换将第一个字母大写变成小写，并在前面加下划线
	 * 
	 * @param args
	 */
	public static String fieldToColumn(String str) {
		char[] chars = str.toCharArray();
		String rstStr = "";
		for (int i = 0; i < chars.length; i++) {
			if (chars[i] > 64 && chars[i] < 94) {
				rstStr += ("_" + chars[i]).toLowerCase();
			}
			else {
				rstStr += chars[i];
			}
		}
		return rstStr;
	}

	/**
	 * 首字母变大写
	 * 
	 * @param args
	 */
	public static String upperCaseFirst(String str) {
		return Character.toUpperCase(str.charAt(0)) + str.substring(1, str.length());
	}

	/**
	 * 首字母变小写
	 * 
	 * @param args
	 */
	public static String lowerCaseFirst(String str) {
		return Character.toLowerCase(str.charAt(0)) + str.substring(1, str.length());
	}

}
